from zope.interface import Interface
from zope.interface import implements
from Acquisition import aq_inner
from plone.memoize.instance import memoize
from Products.CMFCore.utils import getToolByName
from zope.component import getMultiAdapter
from zope.component import queryUtility
from zope.i18n.interfaces import ITranslationDomain
from Products.CMFPlone import utils

from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider

from zope import schema
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from my315ok.xtinfocontent.interfaces import Iclassinfo,Isecondhandinfo,Iinfo

from my315ok.xtinfocontent import xtinfocontentMessageFactory as _
from plone.portlet.collection import PloneMessageFactory as _a

class Iinfoportlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    # TODO: Add any zope.schema fields here to capture portlet configuration
    # information. Alternatively, if there are no settings, leave this as an
    # empty interface - see also notes around the add form and edit form
    # below.

    # some_field = schema.TextLine(title=_(u"Some field"),
    #                              description=_(u"A field to use"),
    #                              required=True)
    name = schema.TextLine(
           title=_(u"info_title"),
           description=_(u"specify title of the portlet "),
           default=u"",
           required=False)
    cssclass = schema.TextLine(
           title=_(u"css class"),
           description=_(u""),
           default=u"",
           required=False)
    limit = schema.Int(title=_a(u"Limit"),
                       description=_a(u"Specify the maximum number of items to show in the portlet. "
                                       "Leave this blank to show all items."),
                       required=False)
    
    infoclass = schema.Choice(title=_(u"info class"),
                       description=_(u"Specify the class of informations."),
                       values=[_(u'classinfo'), _(u'secondhandinfo'), _(u'other')],
                       default=u'classinfo',
                       required=False)


class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(Iinfoportlet)

    # TODO: Set default values for the configurable parameters here

    # some_field = u""

    # TODO: Add keyword parameters for configurable parameters here
    # def __init__(self, some_field=u''):
    #    self.some_field = some_field

    def __init__(self,name=u'',cssclass=None,limit=None,infoclass=None):
        self.name = name
        self.cssclass = cssclass
        self.infoclass = infoclass
        self.limit = limit
        

    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return _(u"InfoPortlet")


class Renderer(base.Renderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('infoportlet.pt')
    def toLocalizedTime(self, time, date_only=None, time_only=None):
        """Convert time to localized time
        """
        fmt = '%Y/%m/%d %H:%M:%S'
        datefmt = '%Y/%m/%d'
        timefmt  = '%H:%M:%S'
        if date_only:
            date = time.strftime(datefmt)
            return date
        elif time_only:
            time = time.strftime(timefmt)
            return time
        else:
            tmp = time.strftime(fmt)
            return tmp
    def isclassinfo(self):
        ic = self.data.infoclass
        if ic =="classinfo":
            return True
        else:
            return False
        
    def header(self):
        return self.data.name
    def css(self):
        return self.data.cssclass
    
    def issecondhandinfo(self):
        ic = self.data.infoclass
        if ic =="secondhandinfo":
            return True
        else:    
            return False
    def isotherinfo(self):
        ic = self.data.infoclass
        if ic =="other":
            return True
        else:
            return False      
    def cropTitle(self,text, length, ellipsis='...'):
        context = aq_inner(self.context)
        pview = getMultiAdapter((context,self.request),name=u"plone")
#        pview = getMultiAdapter((self.parent(), self.request), name=u'earthqk_event_view')
        croped = pview.cropText(text, length)
        return croped
        
        
    @memoize
    def filterinfo(self):
#        import pdb
#        pdb.set_trace()
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')        
        lm = self.data.limit
        result = []
        if self.isclassinfo():
            brains = catalog(object_provides=Iclassinfo.__identifier__,
                             sort="modified",
                             sort_order='reverse',
                             sort_limit=lm)[:lm]
                        
            item={}
            for brain in brains:
                bn = brain.category
#                
                util = queryUtility(ITranslationDomain, 'my315ok.xtinfocontent')
                cn = util.translate(bn,
                                       target_language="zh",
                                       default="qita")
                item["category"] = u"[" + cn + u"]"
                item["url"] = brain.getURL()
                tl = brain.Title
                tl = self.cropTitle(tl, 6)
                item["title"] = tl
                item["modified"] = self.toLocalizedTime(brain.modified, date_only=True)
                result.append(item)
                item={}
            return result
            
        elif self.issecondhandinfo():
            item = {}
            brains = catalog(object_provides=Isecondhandinfo.__identifier__,
                             sort="modified",
                             sort_order='reverse',
                             sort_limit=lm)[:lm]
            for brain in brains:
                tl = brain.Title
                tl = self.cropTitle(tl, 6)
                item["title"] = tl
                item["url"] = brain.getURL()
                item["modified"] = self.toLocalizedTime(brain.modified, date_only=True)
                result.append(item)
                item = {}
            return result
        else:
            item = {}
            brains = catalog(object_provides=Iinfo.__identifier__,
                             sort="modified",
                             sort_order='reverse',
                             sort_limit=lm)[:lm]
            for brain in brains:
                tl = brain.Title
                tl = self.cropTitle(tl, 6)
                item["title"] = tl
                item["url"] = brain.getURL()
                item["modified"] = self.toLocalizedTime(brain.modified, date_only=True)
                result.append(item)
                item = {}
            return result
                 
       


# NOTE: If this portlet does not have any configurable parameters, you can
# inherit from NullAddForm and remove the form_fields variable.

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(Iinfoportlet)

    def create(self, data):
        return Assignment(**data)


# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(Iinfoportlet)
